package com.pj.android.brower.widget

import android.content.Context
import android.util.AttributeSet
import android.view.LayoutInflater
import android.widget.LinearLayout
import com.pj.android.brower.R
import kotlinx.android.synthetic.main.toolbar_layout.view.*

/**
 *Create By hHui on 2018/8/28
 */
class ToolBar : LinearLayout {

    lateinit var toolBar: android.support.v7.widget.Toolbar

    var title: String = ""
        set(value) {
            field = value
            item_title.text = value
        }
        get() {
            return item_title.text.toString()
        }

    var supportBack: Boolean = false
        set(value) {
            field = value
            if (value) item_toolbar.setNavigationIcon(R.drawable.ic_back)
        }

    constructor(context: Context) : super(context)

    constructor(context: Context, attrs: AttributeSet, defStyle: Int) : super(context, attrs, defStyle) {
        initTextAndBackIcon(context, attrs)
    }

    constructor(context: Context, attrs: AttributeSet) : super(context, attrs) {
        initTextAndBackIcon(context, attrs)
    }

    init {
        initView()
    }

    private fun initView() {
        val inflater = context.getSystemService(Context.LAYOUT_INFLATER_SERVICE) as LayoutInflater
        inflater.inflate(R.layout.toolbar_layout, this)
        toolBar = item_toolbar
    }

    /**
     * 初始文字和返回按钮
     */
    private fun initTextAndBackIcon(context: Context, attrs: AttributeSet) {
        val typedArray = context.obtainStyledAttributes(attrs, R.styleable.ToolBar)
        val isSupportBack = typedArray.getBoolean(R.styleable.ToolBar_isSupportBack, false)
        var mText = ""
        if (typedArray.getText(R.styleable.ToolBar_text) != null) {
            mText = typedArray.getText(R.styleable.ToolBar_text).toString()
        }
        typedArray.recycle() //释放资源

        item_title.text = mText
        if (isSupportBack) item_toolbar.setNavigationIcon(R.drawable.ic_back)
    }

}